package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>管理员用户信息 业务实现</p>
 * @package com.itheima.admin.service.impl
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    /**
     * 登录校验
     *
     * @param paramMap
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> paramMap) {
        //获取参数
        String name = paramMap.get("name");
        String password = paramMap.get("password");
        //非空判断
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            throw new LeadNewsException("用户名或者密码错误！");
        }
        //通过用户名查询用户信息
        AdUser adUser = query().eq("name", name).one();
        if (adUser == null) {
            throw new LeadNewsException("用户名或者密码错误！");
        }
        //密码加密处理
        password += adUser.getSalt();
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        //密码校验
        if (!adUser.getPassword().equals(pwd)){
            throw new LeadNewsException("用户名或者密码错误！");
        }
        //校验通过生成token
        String token = AppJwtUtil.createToken(adUser.getId().longValue());
        //构建结果返回
        HashMap<String, Object> result = new HashMap<>();
        result.put("token",token);
        result.put("user",adUser);

        return result;
    }


    //测试代码，获取加密密码
    public static void main(String[] args) {
        System.out.println(DigestUtils.md5DigestAsHex("admin123abc".getBytes()));
    }
}
